import UMe from "../frameSccript/system/OverallSystem ";

export const LAST_PALY_TIME_STORAGE_KEY = "Last-Play-Time";
export const PREVIOUS_PLAY_TIME_STORAGE_KEY = "Previous-Play-Time";

export const LAST_PALY_DATE_STORAGE_KEY = "Last-Play-Date";
export const PREVIOUS_PLAY_DATE_STORAGE_KEY = "Previous-Play-Date";

export interface timeFabric {
    year: number,
    month: number,
    date: number,
    hours: number,
    minutes: number,
    seconds: number,
    millisecondes: number,
    day: number,
}

interface OneSecondsCBList {
    [key: string]: Function;
}

/** 时间插件 */
class TimePlugIn {

    constructor() {
        console.group("TimePlugIn");

        let lPTime = UMe.Servers.localStorageSrv.get(LAST_PALY_TIME_STORAGE_KEY);
        if (lPTime != null && lPTime != "") {
            this.previousPlayTime = JSON.parse(lPTime);
            UMe.Servers.localStorageSrv.set(PREVIOUS_PLAY_TIME_STORAGE_KEY, JSON.stringify(this.previousPlayTime));
            console.log("this.lastPlayTime :", this.timeFabricToString(this.previousPlayTime));
        } else {
            this.lastPlayTime = this.getNowTime();
            UMe.Servers.localStorageSrv.set(LAST_PALY_TIME_STORAGE_KEY, JSON.stringify(this.lastPlayTime));
        }

        let lPDate = UMe.Servers.localStorageSrv.get(LAST_PALY_DATE_STORAGE_KEY);
        if (lPDate != null && lPTime != "") {
            this.previousPlayDate = JSON.parse(lPDate);
            this.OldlastPlayDate = this.previousPlayDate
            this.lastPlayDate = Date.now();
        } else {
            this.previousPlayDate = this.lastPlayDate = this.OldlastPlayDate  = Date.now();
            
        }
        
        UMe.Servers.localStorageSrv.set(LAST_PALY_DATE_STORAGE_KEY, JSON.stringify(this.lastPlayDate));
        UMe.Servers.localStorageSrv.set(PREVIOUS_PLAY_DATE_STORAGE_KEY, JSON.stringify(this.previousPlayDate));

        this.scheduler = cc.director.getScheduler();
        this.scheduler.enableForTarget(this);
        this.scheduler.scheduleUpdate(this, cc.Scheduler.PRIORITY_SYSTEM, false);
        this.scheduler.schedule(this.updateOneSeconds, this, 1);

        console.groupEnd();
    }

    private dateObj: Date = new Date();

    private lastPlayTime: timeFabric = undefined;
    private previousPlayTime: timeFabric = undefined;

    private lastPlayDate: number = undefined;
    private OldlastPlayDate: number = undefined;
    
    private previousPlayDate: number = undefined;

    private scheduler: cc.Scheduler = undefined;

    private oneSecondsCBMap = {};

    /** 获取上次游玩的timeFabric时间 */
    getPreviousPlayTime() {
        if (this.previousPlayTime) {
            return this.previousPlayTime;
        } else {
            return null;
        }
    }

    /** 获取上次游玩的Unix时间 */
    getPreviousPlayDate() {
        return this.previousPlayDate;
    }

    /** 获取上次离线的Unix时间 */
    getPreviousPlayDate2() {
        return this.OldlastPlayDate;
    }

    /** 获取现在的timeFabric时间 */
    getNowTime(): timeFabric {
        let time: timeFabric = {
            year: this.dateObj.getFullYear(),
            month: this.dateObj.getMonth() + 1,
            date: this.dateObj.getDate(),
            hours: this.dateObj.getHours(),
            minutes: this.dateObj.getMinutes(),
            seconds: this.dateObj.getSeconds(),
            millisecondes: this.dateObj.getMilliseconds(),
            day: this.dateObj.getDay(),
        };

        return time;
    }

    timeFabricToString(time: timeFabric): string {
        let str = "";
        str = time.year + "年/"
            + time.month + "月/"
            + time.date + "日/"
            + time.hours + "时/"
            + time.minutes + "分/"
            + time.seconds + "秒/"
            + time.millisecondes + "毫秒/"
            + "星期" + time.day;
        return str;
    }

    /** 刷新最后游戏时间 */
    updateLastPlayTime() {
        this.lastPlayTime = this.getNowTime();
        UMe.Servers.localStorageSrv.set(LAST_PALY_TIME_STORAGE_KEY, JSON.stringify(this.lastPlayTime));
        // console.log("updateLastPlayTime :", this.timeFabricToString(this.lastPlayTime));
        this.lastPlayDate = Date.now();
        UMe.Servers.localStorageSrv.set(LAST_PALY_DATE_STORAGE_KEY, JSON.stringify(this.lastPlayDate));
    }

    /**
     * 设置一个每秒周期回调
     * @param key 属性key
     * @param cb 回调
     */
    setScheduleOneSeconds(key: string, cb: Function) {
        this.oneSecondsCBMap[key] = cb;
    }

    /**
     * 删除一个每秒周期回调
     * @param key 属性key
     */
    deleteScheduleOneSeconds(key: string) {
        delete this.oneSecondsCBMap[key];
    }

    private updateOneSeconds() {
        this.updateLastPlayTime();
        for (const key in this.oneSecondsCBMap) {
            this.oneSecondsCBMap[key] && this.oneSecondsCBMap[key]();
        }
    }

    update(dt) {
        this.dateObj = new Date();
    }


    /**
     * 以秒为单位的数字 转换成 时间格式 的字符串
     * @param num 值
     * @param isHoursShow 是否显示小时
     * @returns 时间格式字符串
     */
    numberShiftTime(num: number, isHoursShow: boolean = false) {
        let str = "";

        let second: number = num % 60;
        let minute: number = (num - second) / 60;
        let hours: number = 0;

        if (minute > 59) {
            let m = minute;
            minute = m % 60;
            hours = (m - minute) / 60;
        }

        if (hours <= 0) {
            if (isHoursShow) {
                str = "00:";
            }
        } else {
            str = `${hours > 9 ? `${hours}` : `0${hours}`}:`;
        }

        if (minute > 0) {
            if (isHoursShow) {
                str = `${str}${minute > 9 ? `${minute}` : `0${minute}`}:`;
            } else {
                str = str == "" ? `${minute > 9 ? `${minute}` : `0${minute}`}:` : `${str}${minute > 9 ? `${minute}` : `0${minute}`}:`;
            }
        } else {
            if (isHoursShow) {
                str = `${str}${minute > 9 ? `${minute}` : `0${minute}`}:`;
            } else {
                str = str == "" ? "00:" : `${str}00:`;
            }
        }

        if (second > 0) {
            str = `${str}${second > 9 ? `${second}` : `0${second}`}`;
        } else {
            str = `${str}00`;
        }

        return str;
    }

    /**
     * 对比timeFabric时间
     * @param target 前一个时间
     * @param source 后一个时间
     * @param span 时间间隔
     * @returns 如果 前一个时间 与 后面一个时间 的间隔大于 输入的时间间隔，返回true，反之返回false
     */
    static compareTime(target: timeFabric, source: timeFabric
        , span: {
            year?: number, month?: number, date?: number,
            hours?: number, minutes?: number, seconds?: number, millisecondes?: number
        }) {

        for (const key in target) {
            if (target.hasOwnProperty(key)) {
                if (key == "day") continue;

                const elemT = target[key];
                const elemS = source[key];
                let offset = Math.max(elemT, elemS) - Math.min(elemT, elemS);
                if (!span[key] && offset > 0) {
                    //console.debug("--------- !span[key] && offset > 0   key:", key, "   target[key] :", target[key], "  source[key] :", source[key]);
                    return true;
                } else if (span[key] && offset >= span[key]) {
                    //console.debug("--------- span[key] && offset >= span[key]   key:", key, "   target[key] :", target[key], "  source[key] :", source[key]);
                    return true;
                } else if (span[key] && offset < span[key]) {
                    //console.debug("--------- span[key] && offset < span[key]   key:", key, "   target[key] :", target[key], "  source[key] :", source[key]);
                    return false;
                }
            }
        }
        return false;
    }

}

let timeS: TimePlugIn = null;
/** 时间服务 */
export default function timePlugIn() {
    if (timeS == null) {
        timeS = new TimePlugIn();
    }
    return timeS;
}
